//global variables 
var stage2 = new createjs.Stage( "canvas-intro" );
var stage = new createjs.Stage( "canvas-main" );
var stage3 = new createjs.Stage( "canvas-outcome" );

var score;
var scoreText;
var attempts;
var attemptText;
var levelText;
var NUMBER_OF_ORBIT_LINES = 3;

var initialPositionX = 150;
var initialPositionY = 250;
var initialVelocityX;
var initialVelocityY;

//width and height for the climber shape
var width = 87;
var height = 100;
//width and height for the quick draw shape
var width2 = 97;
var height2 = 75;

var loadingBar;
var progressValue = 0;
var progressText;

var queue;
var manifest = [ { id: "astro", src: "images/quick-draw3.jpg" },
                   
                 { id: "sate", src: "images/climber13.png" } ];

var LOADING_BAR_WIDTH = 600;
var LOADING_BAR_HEIGHT = 30;

var timestep = 0;
var delta = .3;

var sateContainers = new Array();
var satesImage;
var satesContainer;
var numberOfSates;

var background = new Image();
background.src = "images/rock.jpg";
var backgroundContainer;

var astro = new Image();
astro.src = "images/quick-draw3.jpg";
var astroImage;
var astroContainer;

var planet = new Image();
planet.src = "images/climber13.png";
var planetContainer;

var game = new Game();
game.resetGame();
game.setLevel( 1 );
game.setGameLevel();

//initialize the climbers based on level
function initSateContainers()
{
	//drawing the climbers
	numberOfSates = game.getNumberOfSates();
	var startingX = 600;
	//distances between rope lines
	var intervalX = Math.floor( (stage.canvas.width - startingX ) / NUMBER_OF_ORBIT_LINES - 75 );
	
	for( i = 0; i < numberOfSates; i = i + 1 )
		{
			//draw the climbers
			var sates = new Image();
			sates.src = "images/quick-draw3.jpg";
			satesImage = new createjs.Bitmap( sates );
			satesContainer = new createjs.Container();
			satesContainer.x = startingX + intervalX * i - 50 + 7.5;
			satesContainer.y = game.getSateHeights()[ i ];
			
			var satesShape = new createjs.Shape();
			satesShape.graphics.setStrokeStyle( "1" );
			satesShape.graphics.drawRect( 0, 0, width2, height2 );
			
			satesContainer.addChild( satesImage, satesShape );

			sateContainers.push( satesContainer );
		}	
}
//function that is called as the game loads,
//this function calls the introduction screen
function loadingScreen()
{
	document.getElementById( "velocity" ).style.display = "none";
	document.getElementById( "loading" ).play();
	backgroundContainer = new createjs.Bitmap( background );
	backgroundContainer.x = 0;
	backgroundContainer.y = 0;
	
	stage2.addChild( backgroundContainer );
	
	var text = new createjs.Text( "Hello Fellow Climbers!!", "40px Georgia", "white" );
	text.textAlign = "center";
	text.x = 512;
	text.y = 40;
	
	stage2.addChild( text );
	
	var rules = new createjs.Text( "You and your fellow climber are on the way to \n the mountain summit!\n  " + 
			"Help your partner by tossing her the Quick Draws \n so she can clip in and keep climbing.  \n "+
			"If your partner can catch the Quick Draw, you will climb to the next level. \n" +
			"If your partner can not catch the quick draw,\n you will quickly run out and she will fall! \n " +
			 "If your partner falls the game is over!! \n \n \n" +
			 "DIRECTIONS:  \n Type in the corresponding X and Y coordinates to toss the Quick Draws. \n",
			"19px Georgia", "white" );
	
	rules.textAlign = "center";
	rules.x = 512;
	rules.y = 175;
	
	stage2.addChild( rules );
	
	//code for the play button container on the welcome/introduction canvas
	var containerPlayButton = new createjs.Container();
	
	var playButton = new createjs.Shape();
	playButton.graphics.setStrokeStyle( "3" );
	playButton.graphics.beginStroke( "black" );
	playButton.graphics.beginFill( "#C24641" );
	playButton.graphics.drawRoundRect( 0, 0, 200, 50, 20 );
	
	var playText = new createjs.Text( "CLIMB ON!!!...", "20px Georgia", "black" );
	playText.textAlign = "center";
	playText.x = 200 / 2;
	playText.y = 50 / 3.5;
	
	containerPlayButton.x = 420;
	containerPlayButton.y = 550;
	
	containerPlayButton.addChild( playButton, playText );
	containerPlayButton.addEventListener( "click", playButtonClick );
	
	stage2.addChild( containerPlayButton );
	
	//adds the progress status text next to the loading bar.
	progressText = new createjs.Text( progressValue + "%", "20px Georgia", "red" );
	progressText.textAlign = "center";
	progressText.x = 900;
	progressText.y = 480;
	
	stage2.addChild( progressText );
	
	//draws the loading bar shell 
	var bar = new createjs.Shape();
	bar.graphics.setStrokeStyle( "15" );
	bar.graphics.beginStroke( "#7E3517" );
	bar.graphics.drawRect( 0, 0, LOADING_BAR_WIDTH, LOADING_BAR_HEIGHT );
	
	var barContainer = new createjs.Container();
	barContainer.addChild( bar );
	barContainer.x = stage2.canvas.width / 2 - LOADING_BAR_WIDTH / 2;
	barContainer.y = 475;
		
	stage2.addChild( barContainer );
	
	//draws the loading bar color after the preload is finished
	loadingBar = new createjs.Shape();
	loadingBar.graphics.beginFill( "blue" );
	loadingBar.graphics.drawRect( stage2.canvas.width / 2 - LOADING_BAR_WIDTH / 2, 475, 0, LOADING_BAR_HEIGHT );
	stage2.addChild( loadingBar );
	
	stage2.update();
}
//function that is called when the index.html is opened
function preload()
{
	loadingScreen();
	stage.update();
	
	queue = new createjs.LoadQueue( false );
	
	queue.addEventListener( "fileload", handleFileLoad );
	//queue.addEventListener( "complete", handleComplete );
	
	queue.loadManifest( manifest );
	
	queue.load();
}
//function that handles the drawing and status of the loading bar
function handleFileLoad( evt )
{
	var totalProgress = manifest.length;
	
	progressValue = progressValue + 1;
	
	var percentage = Math.ceil( ( progressValue / totalProgress * 100 ) );
	progressText.text = percentage + "% Loaded";
	
	loadingBar.graphics.beginFill( "#16607d" );
	loadingBar.graphics.drawRect( stage2.canvas.width / 2 - LOADING_BAR_WIDTH / 2, 475, percentage / 100 * LOADING_BAR_WIDTH, LOADING_BAR_HEIGHT );
	stage2.update();
}
//when the play button is clicked on the welcome canvas, the intro canvas is hidden and the main canvas is displayed
function playButtonClick( evt )
{
	document.getElementById( "canvas-main" ).style.display = "inline";
	document.getElementById( "canvas-intro" ).style.display = "none";
	init();
}
//code for the second canvas, the main canvas where everything is played
function init()
{
	stage.removeAllChildren();
	stage.update();
	
	initSateContainers();
	drawBackground();
	drawGameStats();
	drawOrbitAndSates();
	stage.addChild( planetContainer, astroContainer );
	stage.update();
}
//adds the quickdraw image to the main-canvas
astro.onload = function( evt )
{
	astroImage = new createjs.Bitmap( astro );
	astroImage.shadow = new createjs.Shadow( "grey", 5, 5, 5 );
	astroContainer = new createjs.Container();
	astroContainer.x = initialPositionX;
	astroContainer.y = initialPositionY;
	
	var astroShape = new createjs.Shape();
	astroShape.graphics.setStrokeStyle( "1" );
	astroShape.graphics.drawRect( 0, 0, width, height );
	
	astroContainer.addChild( astroImage, astroShape );
	stage.addChild( astroContainer );
	stage.update();
}


//adds the foreground image of a planet
planet.onload = function( evt )
{
	planetContainer = new createjs.Bitmap( planet );
	planetContainer.shadow = new createjs.Shadow( "tan", -5, -5, 5 );
	planetContainer.x = 900;
	planetContainer.y = 800;
	planetContainer.regX = 300;
	planetContainer.regY = 300;
	stage.addChild( planetContainer );
	stage.update();
}
//draws the background image first
function drawBackground()
{
	backgroundContainer = new createjs.Bitmap( background );
	backgroundContainer.x = 0;
	backgroundContainer.y = 0;
	
	stage.addChild( backgroundContainer );
}
//function to write the user game level, number of attempts, and score.
function drawGameStats()
{
	scoreText = new createjs.Text( "Score: " + game.getScore(), "20px comic sands", "red" );
	scoreText.textAlign = "left";
	
	var scoreContainer = new createjs.Container();
	scoreContainer.x = 50;
	scoreContainer.y = 50;
	scoreContainer.addChild( scoreText );

	levelText = new createjs.Text( "Level: " + game.getLevel(), "20px comic sands", "red" );
	levelText.textAlign = "left";
	
	var levelContainer = new createjs.Container();
	levelContainer.x = 50;
	levelContainer.y = 70;
	levelContainer.addChild( levelText );
	
	attemptText = new createjs.Text( "Attempts: " + game.getAttempts(), "20px comic sands", "blue" );
	attemptText.textAlign = "left";
	
	var attemptContainer = new createjs.Container();
	attemptContainer.x = 130;
	attemptContainer.y = 70;
	attemptContainer.addChild( attemptText );
	
	var formBox = new createjs.DOMElement( "velocity" );
	document.getElementById( "velocity" ).style.display = "inline";
	formBox.x = 50;
	formBox.y = 110;
	
	stage.addChild( scoreContainer, levelContainer, attemptContainer, formBox );
}
//Function to draw the ropes and climbers after the game level has loaded
function drawOrbitAndSates()
{
	numberOfSates = game.getNumberOfSates();
	var startingX = 450;
	
	var intervalX = Math.floor( (stage.canvas.width - startingX ) / NUMBER_OF_ORBIT_LINES - 0 );
	
	for( i = 0; i < numberOfSates; i = i + 1 )
		{
			if( game.getSateHeights()[ i ] != -1 /*&& sateContainers[ i ].visible*/ )
				{
					//Draw the climbing ropes
					var orbit = new createjs.Shape();
					orbit.graphics.beginLinearGradientFill( [ "red", "#87CEFF", "black" ], [ 0, .5, 1 ], startingX + intervalX * i, 0, startingX + intervalX * i + 15, 0 );
					orbit.graphics.drawRect( startingX + intervalX * i, 0, 15, stage.canvas.height );
					
					stage.addChild( orbit );
					
					//Draw the climber
					var sates = new Image();
					sates.src = "images/climber13.png";
					satesImage = new createjs.Bitmap( sates );
					satesContainer = new createjs.Container();
					satesContainer.x = startingX + intervalX * i - 365 + 20;
					satesContainer.y = game.getSateHeights()[ i ];
					
					var satesShape = new createjs.Shape();
					satesShape.graphics.setStrokeStyle( "1" );
					satesShape.graphics.drawRect( 0, 0, width2, height2 );
					
					satesContainer.addChild( satesImage, satesShape );
					
					stage.addChild( satesContainer );
				}
		}
	stage.update();
}
//function to redraw the canvas
function redraw()
{
	stage.removeAllChildren();
	stage.update();
	drawBackground();
	drawGameStats();
	drawOrbitAndSates();
	stage.addChild( planetContainer, astroContainer );
	stage.update();
}
//the new two function detail what happens as the launch button is clicked.
createjs.Ticker.setFPS( 24 );
function tick()
{
	initialVelocityX = document.getElementById( "valueX" ).value;
	initialVelocityY = document.getElementById( "valueY" ).value;
	
	astroContainer.x = initialPositionX + initialVelocityX * timestep;
	astroContainer.y = initialPositionY + initialVelocityY * timestep + .5 * 9.81 * timestep * timestep;
	
	timestep = timestep + delta;
	
	planetContainer.rotation += 0;
	
	//check collision here//
	if( isIntersect() )
		{
			var score = game.getScore();
			game.setScore( score + SATE_POINTS );
			scoreText.text = "Score: " + game.getScore();
		}
	
	redraw();
		
	if( astroContainer.y > stage.canvas.height || astroContainer.x > stage.canvas.width )
		{
			createjs.Ticker.removeListener( this );
			document.getElementById( "miss" ).play();
			astroContainer.x = initialPositionX;
			astroContainer.y = initialPositionY;
			timestep = 0;
		}
	stage.update();
}
//function to determine the intersection between the quickdraw and climbers.
//some of the code from http://rhuno.com/flashblog/2012/01/15/tutorial-html-5-space-shooter-part-3/#more-534.
var sateNumber;
var currentSate;
function isIntersect()
{
	sateNumber = sateContainers.length - 1;
		
	for( var i = sateNumber; i >= 0; i = i - 1 )
		{
			currentSate = sateContainers[ i ];
			if( astroContainer.x < sateContainers[ i ].x + width2 &&
					astroContainer.x + width > sateContainers[ i ].x &&
					astroContainer.y < sateContainers[ i ].y + height2 &&
					astroContainer.y + height > sateContainers[ i ].y )
				{
					//sateContainers[ i ].visible = false;
					stage.removeChild( currentSate );
					sateContainers.splice( i, 1 );
					document.getElementById( "hit" ).play();
					console.log( game.getNumberOfSates() + "," + sateNumber );
					stage.update();
					
					var levelNumber = game.getLevel();
					if( sateNumber == 0 )
						{
							createjs.Ticker.removeListener( this );
							game.setLevel( levelNumber + 1);
							game.setGameLevel();
							game.checkGameStatus();
							stage.removeAllChildren();
							//stage.update();
							initSateContainers();
							drawOrbitAndSates();
							astroContainer.x = initialPositionX;
							astroContainer.y = initialPositionY;
						}
					
					return true;
				}
			sateNumber = sateContainers.length - 1;
		}
	return false;
}
//function to be called onclick that starts the animation and adjusts the attempts
function launch()
{
	createjs.Ticker.removeListener( this );
	document.getElementById( "launch" ).play();
	astroContainer.x = initialPositionX;
	astroContainer.y = initialPositionY;
	var numberOfAttempts = game.getAttempts();
	if( numberOfAttempts > 0 )
		{
			game.setAttempts( numberOfAttempts - 1 );
			attemptText.text = "Attempts: " + game.getAttempts();
			createjs.Ticker.addListener( this );
		}
	else
		{
			createjs.Ticker.removeListener( this );
			game.checkGameStatus();
		}
	stage.update();
}
//code for the third canvas, the outcome where loser is displayed
function drawLoserCanvas()
{
	stage3.removeAllChildren();
	stage3.update();
	document.getElementById( "gameover" ).play();
	document.getElementById( "velocity" ).style.display = "none";
	document.getElementById( "canvas-outcome" ).style.display = "inline";
	document.getElementById( "canvas-main" ).style.display = "none";
		
	backgroundContainer;
	
	var outcomeLText = new createjs.Text( "OOPS! You made the climber fall!!!\n\n\n", "40px Georgia", "red" );
	outcomeLText.text += "Stay Calm. Climb On. Start Over!!";
	outcomeLText.textAlign = "center";
	outcomeLText.x = 512;
	outcomeLText.y = 200;
	
	stage3.addChild( backgroundContainer, outcomeLText );
	stage3.update();	
}
//code for the third canvas, the outcome where winner is displayed
function drawWinnerCanvas()
{
	stage3.removeAllChildren();
	stage3.update();
	document.getElementById( "winner" ).play();
	document.getElementById( "velocity" ).style.display = "none";
	document.getElementById( "canvas-outcome" ).style.display = "inline";
	document.getElementById( "canvas-main" ).style.display = "none";
		
	backgroundContainer;
	
	var outcomeWText = new createjs.Text( "You have helped the climber reach the summit!! You win!!!\n\n", "40px Georgia", "yellow" );
	outcomeWText.text += "Winner!!";
	outcomeWText.textAlign = "center";
	outcomeWText.x = 512;
	outcomeWText.y = 200;
	
	stage3.addChild( backgroundContainer, outcomeWText );
	stage3.update();	
}